package cn.jekun.shop.web.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.MD5;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.RsUserShop;
import cn.jekun.component.core.service.SMSService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.core.service.gen.RsUserShopService;
import cn.jekun.component.core.validator.annotation.UserName;
import cn.jekun.shop.common.service.ShopBaseService;
import cn.jekun.shop.web.bean.User;

@Service(LoginService.BEAN_NAME)
public class LoginService extends ShopBaseService {
	public static final String BEAN_NAME = "cn.jekun.shop.web.service.LoginService";
	public static final String NAMESPACE = "SHOP_MEMBER_USER";

	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;

	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService userService;
	
	@Resource(name=RsUserShopService.BEAN_NAME)
	RsUserShopService rsUserShopService;

	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public JSONObject login(
			@UserName
			String userName,
			//@Password
			@NotBlank(message="密码不能为空")
			@MD5(message="密码格式不正确")//MD5加密
			String password) {
		
		
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(userName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户名不能为空");
		}
		if (StringUtils.isBlank(password)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"密码不能为空");
		}
		Map tempUserMap = new HashMap();
		// 通過userName的用户是否存在

		//SqlUtis.prepareSql(tempUserMap, "","and (b.user_name='"+userName+"' or b.mobile='"+userName+"')");
		SqlUtis.prepareSql(tempUserMap, "","and b.mobile='"+userName+"'");
		User rsUser = this.one(tempUserMap);
		if (rsUser == null) {
			SqlUtis.prepareSql(tempUserMap, "","and b.user_name='"+userName+"'");
			rsUser = this.one(tempUserMap);
		}
		if (rsUser == null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		} else {
			String pwd = rsUser.getPassword();
			// 密码不为空并且密码相同则将会员的信息保存到session并且登录成功，反之失败返回登录页面
			if (pwd != null && pwd.equals(/*EncryptUtil.md5(*/password/*)*/)) {
				jsonObject.put("userId", rsUser.getUserId());
				jsonObject.put("userName", rsUser.getUserName());
				jsonObject.put("mobile", rsUser.getMobile());
				jsonObject.put("iconUrl", rsUser.getIconUrl());
				List list=this.listBySql("select b.shop_id shopId,b.shop_name shopName,b.print_type from RS_USER_SHOP a  join ERP_SHOP b on(a.shop_id=b.shop_id)  where a.user_id='"+rsUser.getUserId()+"'");
				if(list!=null && list.size()>0){
					
					Map map=(Map) list.get(0);
					jsonObject.put("shopId", map.get("SHOPID"));
					jsonObject.put("shopName", map.get("SHOPNAME"));
					jsonObject.put("printType", map.get("PRINT_TYPE"));
				}else{
					jsonObject.put("shopId", "");
					jsonObject.put("shopName", "");
					jsonObject.put("printType", "");
				}
				
				list=this.listBySql("select b.agent_id agentId,b.agent_Name agentName,b.mobile mobile from RS_USER_AGENT a  join RS_AGENT b on(a.agent_id=b.agent_id)  where a.user_id='"+rsUser.getUserId()+"'");
				if(list!=null && list.size()>0){
					
					Map map=(Map) list.get(0);
					jsonObject.put("agentId", map.get("AGENTID"));
					jsonObject.put("agentName", map.get("AGENTNAME"));
					jsonObject.put("agentMobile", map.get("MOBILE"));
				}else{
					jsonObject.put("agentId", "");
					jsonObject.put("agentName", "");
					jsonObject.put("agentMobile", "");
				}
			
				/*Map tempMap = new HashMap();
				tempMap.put(RsUser.COL_USER_ID, rsUser.getUserId());
				SqlUtis.prepareSql(tempMap, 
						SqlUtis.getSQL(tempMap, "a."+RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
				RsUserShop tempUserShop = rsUserShopService.one(tempMap);
				if(tempUserShop != null){
					jsonObject.put("shopId", tempUserShop.getShopId());
					//jsonObject.put("shopName", tempUserShop);
				}else{
					jsonObject.put("shopId", "");
				}*/
				return executeRerutn(jsonObject);
			} else {
				throw new BusinessException(
						Constants.ERRORS.VALIDATE_ERROR_CODE, "用户名密码错误");
			}
		}
	}
	/**
	 * 退出
	 * @return
	 */
	public JSONObject logout(){
		JSONObject jsonObject = new JSONObject();
		return executeRerutn(jsonObject);
	}



	/**
	 * 找回登录密码，发送手机验证码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject sendValidateCode(@Mobile(message="手机号码格式不正确")String mobile){

		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号码不能为空");
		}

		Map tempUserMap = new HashMap();

		tempUserMap.put(User.COL_MOBILE, mobile);

		SqlUtis.prepareSql(tempUserMap, "", SqlUtis.getSQL(tempUserMap, "b."
				+ User.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
		User rsUser = this.one(tempUserMap);
		if (rsUser == null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}else{
			SMSService.checkTime(mobile);//检查发送间隔
			//一天最多5条
			if(!this.smsService.checkOverTimes(mobile, 	Constants.RS_SMS_TYPE.RE_LOGIN_PWD, "24", 5)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"一天最多5条,请稍后再操作");
			}
			//发送手机验证码
			try {
				// 生成随机类
				Random random = new Random();
				// 取随机产生的认证码(4位数字)
				String sRand = "";
				for (int i = 0; i < 6; i++) {
					String rand = String.valueOf(random.nextInt(10));
					sRand += rand;
				}
				String content = "您正在找回登录密码，验证码"+sRand+"，请在页面填写，如非本人操作，请忽略。" ;
//				// 将认证码存入数据库
//				Map insertMap = new HashMap();
//				RsSms rsSms = new RsSms();
//				rsSms.setContent(content);
//				rsSms.setMemo(sRand);
//				rsSms.setMobile(mobile);
//				rsSms.setSmsTypeId(Constants.RS_SMS_TYPE.RE_LOGIN_PWD);// 找回登录密码验证码
//				insertMap.put("rsSms", rsSms);
//				rsSmsService.insert(insertMap);
				// 发送短信
				String error = this.smsService.sendSMS(mobile, content, Constants.RS_SMS_TYPE.RE_LOGIN_PWD, sRand);
				if (error != null) {
					jsonObject.put(ErrorMsg.KEY_MESSAGE, error);
					return this.executeRerutnFail(jsonObject);
				}
				return this.executeRerutn(jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
				return this.executeRerutnFail(jsonObject);
			}
		}
	}

	/**
	 * 验证短信验证码是否正确
	 * @param mobile
	 * @param validatecode
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject checkValidateCode(@Mobile(message="手机号码格式不正确")String mobile,@Num(length=6,message="短信验证码格式不正确")String validateCode){

		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号码不能为空");
		}
		if (StringUtils.isBlank(validateCode)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"短信验证码不为空");
		}
		JSONObject jsonObject = new JSONObject();
		// 短信验证码验证（查找最新的短信信息验证码）
		String tempCode = null;// 手机验证码
		Map tempSmsMap = new HashMap();
		tempSmsMap.put(RsSms.COL_MOBILE, mobile);
		tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.RE_LOGIN_PWD);
		SqlUtis.prepareSql(tempSmsMap, "", 
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.orderBy(" a.create_time desc nulls last"));
		Page smsPage = new Page();
		smsPage.setPageSize(1);
		List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
		if (smsList != null && smsList.size() == 1) {
			RsSms rsSms = smsList.get(0);
			tempCode = rsSms.getMemo();
		}
		if (!validateCode.equals(tempCode)) {
			throw new BusinessException("-3210",
					"验证码错误");
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 重置登录密码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject reLoginPwd(@MD5(message="密码格式不正确")//MD5加密
								String newPwd,@Mobile(message="手机号码格式不正确")String mobile){

		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号码不能为空");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"密码不能为空");
		}
		JSONObject jsonObject = new JSONObject();

		try {
			Map tempUserMap = new HashMap();
			tempUserMap.put(User.COL_MOBILE, mobile);
			SqlUtis.prepareSql(tempUserMap, "", SqlUtis.getSQL(tempUserMap, "b."
					+ User.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
			User rsUser = this.one(tempUserMap);
			if (rsUser == null) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"用户不存在");
			}else{	
				Map map = new HashMap();
				RsUser user = new RsUser();
				map.put("rsUser", user);
				map.put(RsUser.COL_USER_ID, rsUser.getUserId());
				user.setPassword(/*EncryptUtil.md5(*/newPwd/*)*/);
				user.setResetPassword("");
				SqlUtis.prepareSql(map
						, SqlUtis.getSQLRequired(map,"a."+RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
				this.userService.update(map);
				return executeRerutn(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return this.executeRerutnFail(jsonObject);
		}
		
	}  

}
